const https = require('https');
let SQLhelper = require('./SQLhelper');
const snowflake = require('./snowflake');
let tokens = {}
// const {JSON}= require('mysql/lib/protocol/constants/types');
SQLhelper(`select * from  member`).then(res => {
    console.log("i am mysql", res);
})

module.exports = function (app) {
    //登录拦截中间件
    function loginRouter(req, res, next) {
        let token = req.headers.token
        if (token) {
            let session = tokens[token]
            if (session) {
                req.session = session
                next()
            } else {
                res.status(406).send({
                    errMsg: '当前用户未登陆'
                })
            }
        } else {
            res.status(405).send({
                errMsg: '缺少token，请先进行登录'
            })
        }
    }

    //日期格式化
    const formatTime = date => {
        const year = date.getFullYear()
        const month = date.getMonth()
        const day = date.getDate()
        const hour = date.getHours()
        const minute = date.getMinutes()
        const second = date.getSeconds()

        return `${[year,month,day].map(formatNumber).join('/')} ${[hour,minute,second].map(formatNumber).join(':')}`
    }
    const formatNumber = n => {
        n = n.toString()
        return n[1] ? n : `0${n}`
    }
    // app.get('/wx/login',(req,res)=>{
    //     console.log(req.headers);
    //     let code=req.query.code
    //      let appid = 'wx2bd09bfc743d6085'
    //      let secret = '8cfa0c788ddff119408acff770d9509d'
    //      https.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`, (ret) => {  
    //                  ret.on('data', (d) => {
    //                      res.send(d.toString())
    //                  });

    //              }).on('error', (e) => {
    //                  console.error(e);
    //              });
    // })


    app.use('/wx', loginRouter)
    //微信登录
    // app.listen(port, () => {
    //     console.log(`Example app Listening on port ${port}`);
    // })
    // app.use(express.static('www'))
    // app.listen(port, () => {
    //     console.log(`Example app Listening on port ${port}`);
    // })
    // app.use(express.static('www'))
    app.get('/wxlogin', (req, res) => {
        let code = req.query.code
        let appid = 'wx2bd09bfc743d6085'
        let secret = '8cfa0c788ddff119408acff770d9509d'
        https.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`, (ret) => {
            ret.on('data', (ret) => {
                ret = JSON.parse(ret.toString())
                let openid = ret.openid
                if (!openid) {
                    res.send({
                        errorMsg: ret.errMsg || '获取openid错误'
                    })
                } else {
                    let queryMember = `select * from member where openId ='${openid}'`
                    let token = new Date().getTime()
                    SQLhelper(queryMember).then(membersRet => {
                        // console.log(membersRet)
                        if (membersRet.length) { //用户已经存在
                            let member = membersRet[0]
                            let token=snowflake()
                            tokens[token] = member
                            member.token = token
                            SQLhelper(`
    INSERT INTO session(id,userId,userName,inTime,platform) 
    VALUES(${token},'${member._id}','${member.nickName}','${formatTime(new Date())}','wx')
    `).then(ret => {
                                res.send({
                                    nickName: member.nickName,
                                    token,
                                    openId: member.openId,
                                    avatarUrl: member.avatarUrl,
                                    _id: member._id
                                })
                            })
                        } else { //用户不存在 使用openid注册用户
                            SQLhelper(`INSERT INTO member(openId) values('${openid}')`).then(newMember => {
                                //注册成功 返回新用户信息
                                SQLhelper(queryMember).then(newMember => {
                                    SQLhelper(`
    INSERT INTO session(id,userId,userName,inTime,platform) 
    VALUES(${token},'${member._id}','${member.nickName}','${formatTime(new Date())}','wx')
    `).then(ret => {
                                        let member = membersRet[0]
                                        let token=snowflake()
                                        tokens[token] = member
                                        member.token = token
                                        res.send({
                                            nickName: member.nickName,
                                            token,
                                            openId: member.openId,
                                            avatarUrl: member.avatarUrl,
                                            _id: member._id
                                        })
                                    })
                                })
                            })
                        }
                    })
                }
            }).on('error', (e) => {
                console.error(e)
                res.send({
                    errorMsg: '获取openId错误'
                })
            });
        })
    })


    // 修改用户信息
    app.put('/wx/member', (req, res) => {
        let userInfo = req.body
        console.log("sadad", req.body);
        SQLhelper(`update member set nickName='${userInfo.nickName}',avatarUrl='${userInfo.avatarUrl}'
     where _id='${userInfo._id}'`).then(ret => {
            console.log(ret)
            res.send({})
        })
    })

    // 获取收获地址
    app.get('/wx/address',(req, res) => {
        // let session=tokens[req.headers.token]
        // console.log("ssss",session);
        if (req.session._id) {
            SQLhelper(`select * from address where state=1 and memberId =${req.session._id}`)
                .then(ret => {
                    res.send(ret)
                })
        } else {
            res.send({
                errorMsg: '请传入memberId'
            })
        }
    })

    //获取地址详情
    app.get('/wx/address/detail', (req, res) => {
        console.log("sada", req.query.addressId);
        if (req.query.addressId) {
            SQLhelper(`select * from address where _Id =${req.query.addressId}`)
                .then(ret => {
                    res.send(ret.length ? ret[0] : {
                        errorMsg: '为获取地址详情'
                    })
                })
        } else {
            res.send({
                errorMsg: '请传入addressId'
            })
        }
    })

    // 新增收获地址
    app.post('/wx/address', (req, res) => {
        console.log("sada", req.body.memberId);
        if (req.body.memberId && req.body.receiver && req.body.phone && req.body.city) {
            SQLhelper(`insert into address(state,memberId,receiver,phone,city,area) values('1','${req.body.memberId}','${req.body.receiver}','${req.body.phone}'
             ,'${req.body.city}','${req.body.area || ''}')`)
                .then(ret => {
                    res.send(ret)
                })
        } else {
            res.send({
                errorMsg: '请传入memberId'
            })
        }
    })

    //修改默认地址
    app.put('/wx/address/default', (req, res) => {
        let addressId = req.body.addressId,
            memberId = req.body.memberId,
            isDefault = req.body.isDefault == 1 ? 1 : 0
        if (addressId && memberId) {
            if (isDefault == 1) {
                SQLhelper(`update address
            set isDefault=0 
            where isDefault=1 and memberId=${memberId}`)
                    .then(ret => {
                        SQLhelper(`update address
            set isDefault=1 
            where _id=${addressId}`).then(ret => {
                            res.send(ret)
                        })
                    })
            } else {
                SQLhelper(`update address
            set isDefault=0 
            where _id=${addressId}`).then(ret => {
                    res.send(ret)
                })
            }
        } else {
            res.send({
                errorMsg: "参数错误"
            })
        }
    })

    //删除地址
    app.delete('/wx/address', (req, res) => {
        let addressId = req.body.addressId
        console.log("asdasd",addressId);
        if (addressId) {
            SQLhelper(`update address
            set state=0
            where _id=${addressId}`)
                .then(ret => {
                    res.send(ret)
                })
        } else {
            res.send({
                errorMsg: "参数错误"
            })
        }

    })

}